<?php

namespace app\admin\controller\finance;

use addons\shopro\model\UserWalletLog;
use app\admin\model\shopro\Agentstore;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;


/**
 * 订单按日汇总
 *
 * @icon fa fa-circle-o
 */
class Orderstatusrpt extends Backend
{
    /**
     * Activity模型对象
     * @var \app\admin\model\shopro\activity\Retailorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);

            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            list($where, $sort, $order, $offset, $limit,$page) = $this->buildparams();

            $where = "id > 0 ";
            if(isset($filter['date'])){
                $rawdate = $filter['date'];
                $rawdate = str_replace(' - ', ',', $rawdate);
                $arr = array_slice(explode(',', $rawdate), 0, 2);

                $where .= " and createtime > '". strtotime($arr[0]) . "' and createtime < '". strtotime($arr[1]) . "'";
            }

            //总数
            $totalsql = "SELECT FROM_UNIXTIME(createtime,'%Y-%m-%d') as date from fa_shopro_order where {$where} group by date";
            $totaldata = Db::query($totalsql);

            //详细数据
            $sql = "SELECT date, 
	max(case `status` when '-2' then cnt else 0 end) 'close',
	max(case `status` when '-1' then cnt else 0 end) 'cancel',
	max(case `status` when '0' then cnt else 0 end) 'nopay',
	max(case `status` when '1' then cnt else 0 end) 'payed',
	max(case `status` when '2' then cnt else 0 end) 'finish',
	max(case `status` when '1' then total_amount else 0 end) 'payed_amount',
	max(case `status` when '2' then total_amount else 0 end) 'finish_amount'
from
(SELECT sum(total_amount) as total_amount,FROM_UNIXTIME(createtime,'%Y-%m-%d') as date,status,count(1) as cnt from fa_shopro_order where {$where} group by status,date order by date) as rpt
group by date limit {$offset},{$limit}";

            $retdata = Db::query($sql);

            $totaldata = $this->total($retdata);
            if(!empty($totaldata)){
                //不为空
                $retdata[] = $totaldata;
            }

            $result = array("total" => count($totaldata), "rows" => $retdata);

            return json($result);
        }
        return $this->view->fetch();
    }

    protected function total($retdata)
    {
        //汇总
        $totaldata = [];
        if(!empty($retdata[0])){
            foreach ($retdata[0] as $k=>$v){
                if($k=='date'){
                    $totaldata[$k] = '汇总';
                }else{
                    $totaldata[$k] = 0;
                }
            }
        }

        foreach ($retdata as $item) {
            $totaldata['cancel'] = round($totaldata['cancel'] + $item['cancel'], 2);
            $totaldata['close'] = round($totaldata['close'] + $item['close'], 2);
            $totaldata['nopay'] = round($totaldata['nopay'] + $item['nopay'], 2);
            $totaldata['payed'] = round($totaldata['payed'] + $item['payed'], 2);
            $totaldata['finish'] = round($totaldata['finish'] + $item['finish'], 2);
            $totaldata['payed_amount'] = round($totaldata['payed_amount'] + $item['payed_amount'], 2);
        }

        return $totaldata;
    }

}
